﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.MaterialInfoCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.MaterialInfoCommandHandler
{
    /// <summary>
    /// 物料信息新增命令处理
    /// </summary>
    public class MaterialInfoCreateCommandHandler : IRequestHandler<MaterialInfoCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// 物料信息仓储
        /// </summary>
        private readonly IBaseRepository<MaterialInfo> materialRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="materialRepository">物料信息仓储</param>
        /// <param name="mapper">映射</param>
        public MaterialInfoCreateCommandHandler(IBaseRepository<MaterialInfo> materialRepository,IMapper mapper)
        {
            this.materialRepository = materialRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<object>> Handle(MaterialInfoCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            DateTime date = DateTime.Now;
            string dateString = date.ToString("HHmm");
            string bianma = dateString;

            var obj = mapper.Map<MaterialInfo>(request);

            obj.MaterialInfoCode = "xs" + bianma;
            obj.MaterialStatu = "未审批";
            var r = materialRepository.AddAsync(obj).Result;

            if (r > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = r;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
                result.data = r;
            }

            return Task.FromResult(result);
        }
    }
}
